﻿/*
 * ASP.NET Validation Controls for MVC (using WebUIValidation.js)
 *
 * Copyright (c) 2009 Guramrit Singh Dhillon
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using Classic.Mvc.Web.UI.Validators;

namespace Classic.Mvc.Web.UI
{
    public class ValidatorScriptManager : Control
    {
        private static readonly Type _type = typeof (ValidatorScriptManager);

        public static ValidatorScriptManager Current
        {
            get { return (HttpContext.Current == null) ? null : HttpContext.Current.Items[_type] as ValidatorScriptManager; }

            private set
            {
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.Items[_type] = value;
                }
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (!DesignMode)
            {
                if (Current != null)
                {
                    throw new InvalidOperationException("Cannot have more than one Validation Script Manager.");
                }

                Current = this;
            }
        }

        private readonly List<IMvcControl> _validators = new List<IMvcControl>();

        internal void AddValidationControl(IMvcControl control)
        {
            _validators.Add(control);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            writer.WriteLine("<script type=\"text/javascript\" src=\"{0}\"></script>",
                             Page.ClientScript.GetWebResourceUrl(
                                 typeof (Page),
                                 "WebUIValidation.js"));
            writer.WriteLine("<script type=\"text/javascript\">");
            writer.WriteLine("//<![CDATA[");
            writer.WriteLine("var Page_ValidationSummaries = new Array({0});",
                             string.Join(", ",
                                         (from validator in _validators.OfType<ValidationSummary>()
                                          select string.Format("document.getElementById(\"{0}\")", validator.ID))
                                             .ToArray()));
            writer.WriteLine("var Page_Validators = new Array({0});",
                             string.Join(", ",
                                         (from validator in _validators.OfType<BaseValidator>()
                                          select string.Format("document.getElementById(\"{0}\")", validator.ID))
                                             .ToArray()));
            writer.WriteLine("(function(){");
            foreach (var validator in _validators)
                writer.Write(validator.GetScript());
            writer.WriteLine("})();");

            writer.WriteLine("var Page_ValidationActive = false;");
            writer.WriteLine("if (typeof(ValidatorOnLoad) == \"function\")");
            writer.WriteLine("ValidatorOnLoad();");
            writer.WriteLine("//]]>");
            writer.WriteLine("</script>");
        }
    }
}